package hu.bme.mit.rifl.business.base;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.InitialContext;

/**
 * Wrapper facade for establishing the connection to the JMS provider and for
 * sending and receiving work items.
 */
public abstract class RiflOrderQueue {

	protected String queueName;
	protected InitialContext ic;
	protected Queue queue;
	protected Connection connection;
	protected Session session;

	public RiflOrderQueue(String queueName) {
		this.queueName = queueName;
		setupEnvironment();
	}

	/**
	 * Closes the connection to the manager.
	 */
	public void close() {
	}

	/**
	 * Sets the Environment, i.e.: calls for initial context, session and
	 * creates a Queue
	 */
	protected void setupEnvironment() {
		try {
			setSession();
			this.queue = (Queue) ic.lookup("/queue/" + this.queueName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Creates a session.
	 */
	public void setSession() throws Exception {
		this.ic = getContext();
		ConnectionFactory cf = (ConnectionFactory) ic
				.lookup("/ConnectionFactory");
		this.connection = cf.createConnection();
		this.session = connection
				.createSession(false, Session.AUTO_ACKNOWLEDGE);
	}

	/**
	 * Creates and returns a new InitialContext.
	 */
	protected InitialContext getContext() throws Exception {
		String jndiFilename = "jndi.properties";
		File jndiFile = new File(jndiFilename);
		Properties props = new Properties();
		FileInputStream inStream = null;
		try {
			inStream = new FileInputStream(jndiFile);
			props.load(inStream);
		} catch (Exception e) {
		} finally {
			if (inStream != null) {
				inStream.close();
			}
		}
		return new InitialContext(props);
	}
}
